package com.ruoyi.web.controller.laiqianba.member;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.db.domain.MemberBaseInfo;
import com.ruoyi.db.domain.MemberLoginSession;
import com.ruoyi.db.domain.MemberSourceInfo;
import com.ruoyi.db.domain.SourceMemberDataInfoHistory;
import com.ruoyi.laiqianba.constant.RedisKeyConstant;
import com.ruoyi.laiqianba.service.IMemberSourceDictInfoService;
import com.ruoyi.member.service.IMemberAuthInfoService;
import com.ruoyi.member.service.IMemberBaseInfoService;
import com.ruoyi.member.service.IMemberLoginSessionService;
import com.ruoyi.member.service.IMemberSourceInfoService;
import com.ruoyi.web.wrapper.MemberSourceInfoWrapper;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户资质信息Controller
 *
 * @author ruoyi
 * @date 2023-08-13
 */

@RestController
@RequestMapping("/member/sourceInfo")
public class MemberSourceInfoController extends BaseController {
    @Autowired
    private IMemberSourceInfoService memberSourceInfoService;
    @Autowired
    private IMemberBaseInfoService memberBaseInfoService;
    @Autowired
    private IMemberAuthInfoService memberAuthInfoService;
    @Autowired
    private IMemberSourceDictInfoService memberSourceDictInfoService;
    @Autowired
    private IMemberLoginSessionService  memberLoginSessionService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * 查询用户资质信息列表
     */
    @PreAuthorize("@ss.hasPermi('member:sourceInfo:list')")
    @GetMapping("/list")
    public TableDataInfo list(MemberSourceInfo memberSourceInfo) {
        startPage();
        List<Map<String, Object>> list = memberSourceInfoService.selectMemberSourceInfoMapList(memberSourceInfo);

        Map<String, String> sourceDictMap = memberSourceDictInfoService.selectSourceDictMap();
        list = new MemberSourceInfoWrapper(list).setSourceDictMap(sourceDictMap).wrap();
        return getDataTable(list);
    }


    @GetMapping("/city")
    public AjaxResult getCity(MemberSourceInfo memberSourceInfo) {

        JSONObject returnData = new JSONObject();
        if(StrUtil.equals(memberSourceInfo.getType(),"1")){
            returnData.put("cityList", memberSourceInfoService.getCity(memberSourceInfo));
        } else {
            returnData.put("cityList", memberSourceInfoService.getCityList(memberSourceInfo));
        }
        return AjaxResult.success(returnData);
    }

    /**
     * 查询用户资质信息  卡片版
     */
    @PreAuthorize("@ss.hasPermi('member:sourceInfo:card')")
    @GetMapping("/card")
    public TableDataInfo card(MemberSourceInfo memberSourceInfo) {
        startPage();
        List<Map<String, Object>> list = memberSourceInfoService.selectMemberSourceInfoCardList(memberSourceInfo);
        list = new MemberSourceInfoWrapper(list).wrap();
        return getDataTable(list);
    }


    /**
     * 获取用户资质信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('member:sourceInfo:query')")
    @GetMapping(value = "/{uid}")
    public AjaxResult getInfo(@PathVariable("uid") Long uid) {
        return success(memberSourceInfoService.selectMemberSourceInfoByUid(uid));
    }

    /**
     * 新增用户资质信息
     */

    @PreAuthorize("@ss.hasPermi('member:sourceInfo:add')")
    @Log(title = "用户资质信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MemberSourceInfo memberSourceInfo) {
        return toAjax(memberSourceInfoService.insertMemberSourceInfo(memberSourceInfo));
    }

    /**
     * 修改用户资质信息
     */
    @PreAuthorize("@ss.hasPermi('member:sourceInfo:edit')")
    @Log(title = "用户资质信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MemberSourceInfo memberSourceInfo) {
        return toAjax(memberSourceInfoService.updateMemberSourceInfo(memberSourceInfo));
    }

    /**
     * 删除用户资质信息
     */
    @PreAuthorize("@ss.hasPermi('member:sourceInfo:remove')")
    @Log(title = "用户资质信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{uids}")
    public AjaxResult remove(@PathVariable Long[] uids) {
        return toAjax(memberSourceInfoService.deleteMemberSourceInfoByUids(uids));
    }

    /**
     * 删除和修改
     */
    @PreAuthorize("@ss.hasPermi('member:sourceInfo:remove')")
    @Log(title = "用户资质信息", businessType = BusinessType.DELETE)
    @PostMapping("/del")
    public AjaxResult remove(@RequestBody MemberBaseInfo memberBaseInfo) {

        if(memberBaseInfo.getTypes()==null && StringUtils.isEmpty(memberBaseInfo.getTypes())){
            return AjaxResult.error("请选择想要重置的类型");
        }
        boolean Auth = memberBaseInfo.getTypes().contains("1");
        boolean Source = memberBaseInfo.getTypes().contains("0");


        Long uid = memberBaseInfo.getUid();
        String mobile = memberBaseInfo.getMobile();

        // 如果用户ID为空且手机号不为空，根据手机号查询用户ID
        if (uid == null && !StringUtils.isEmpty(mobile)) {
            MemberBaseInfo findByPhone = memberBaseInfoService.selectUidByPhone(mobile);
            if (findByPhone != null) {
                uid = findByPhone.getUid();
                memberBaseInfo.setUid(uid);
            } else {
                return AjaxResult.error("请输入正确的手机号/手机号不存在");
            }
        }
        if (Auth) {
            int i1 = memberAuthInfoService.deleteMemberAuthInfoByUid(memberBaseInfo.getUid());
            memberBaseInfo.setAuthFlag(0L);
            memberBaseInfo.setFaceFlag(0L);
        }

        if (Source) {
            int i = memberSourceInfoService.deleteMemberSourceInfoByUid(memberBaseInfo.getUid());
            memberBaseInfo.setSourceFlag(0L);
        }
       List<MemberLoginSession> memberLoginSessionList = memberLoginSessionService.getTokenByUid(memberBaseInfo.getUid());

        for (MemberLoginSession memberLoginSession : memberLoginSessionList) {
            String token = memberLoginSession.getToken();
            String key = RedisKeyConstant.TOKEN_REDIS_KEY_PREFIX+ token;
            stringRedisTemplate.delete(key);
        }

        return toAjax(memberBaseInfoService.updateMemberBaseInfo(memberBaseInfo));
    }

    @PostMapping("/upload")
    public TableDataInfo upload(@RequestParam("file") @RequestBody MultipartFile file)  throws IOException {

        List<String> md5List = parseExcel(file);
        List<Map<String, Object>> list = memberSourceInfoService.upload(md5List);
        return getDataTable(list);
    }
    private List<String> parseExcel(MultipartFile file) throws IOException {
        List<String> md5List = new ArrayList<>();

        try (InputStream is = file.getInputStream();
             Workbook workbook = WorkbookFactory.create(is)) {
            Sheet sheet = workbook.getSheetAt(0);
            for (Row row : sheet) {
                if (row.getRowNum() == 0) continue;
                Cell cell = row.getCell(0);
                if (cell != null) {
                    String md5 = cell.toString().trim();
                    if (md5.matches("^[a-fA-F0-9]{32}$")) {
                        md5List.add(md5.toLowerCase());
                    }
                }
            }
        }
        return md5List;
    }


}
